package com.logica.mdm.webfrontend.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * URL utilities.
 * @author Fabien Crespel <fabien.crespel@logica.com>
 */
public class URLUtils {
	
	/**
	 * Build a full URL by joining a base URL and a query string (if any).
	 * @param baseUrl URL up to but not including the query string
	 * @param query query string (can be null)
	 * @return full URL
	 */
	public static String buildUrl(String baseUrl, String query) {
		String ret = baseUrl;
		if (!StringUtils.isEmpty(query))
			ret += "?" + query;
		return ret;
	}
	
	/**
	 * Build a full URL by joining a base URL and building a query string from a map.
	 * @param baseUrl URL up to but not including the query string
	 * @param query query string map
	 * @return full URL
	 */
	public static String buildUrl(String baseUrl, Map<String, String> query) {
		List<String> queryPairs = new ArrayList<String>();
		for (Entry<String, String> entry : query.entrySet()) {
			try {
				String keyEncoded = URLEncoder.encode(entry.getKey(), "UTF-8");
				String valueEncoded = entry.getValue() == null ? "" : URLEncoder.encode(entry.getValue(), "UTF-8");
				queryPairs.add(keyEncoded + "=" + valueEncoded);
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
		}
		
		return buildUrl(baseUrl, StringUtils.join(queryPairs.toArray(), "&"));
	}
	
	/**
	 * Get the HTTP servlet request URI without the context path.
	 * @param request
	 * @return request URI without the context path
	 */
	public static String getRequestURIWithoutContext(HttpServletRequest request) {
		return StringUtils.removeStart(request.getRequestURI(), request.getContextPath());
	}

}
